const express = require('express');
const router = express.Router();
const DriftBottle = require('../models/DriftBottle');
const { authenticateToken } = require('../middleware/auth');
const { body, validationResult } = require('express-validator');

/**
 * 扔出漂流瓶
 * POST /drift-bottles
 */
router.post('/', 
  authenticateToken,
  [
    body('content')
      .notEmpty()
      .withMessage('漂流瓶内容不能为空')
      .isLength({ max: 500 })
      .withMessage('漂流瓶内容不能超过500个字符')
  ],
  async (req, res) => {
    try {
      // 参数验证
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({
          code: 400,
          success: false,
          message: '参数验证失败',
          errors: errors.array()
        });
      }

      const { content } = req.body;
      const userId = req.user.userId;

      // 创建漂流瓶
      const bottle = await DriftBottle.create(userId, content);

      res.status(200).json({
        code: 200,
        success: true,
        message: '漂流瓶发送成功',
        data: {
          bottleId: bottle.id,
          content: bottle.content,
          createdAt: bottle.createdAt
        }
      });
    } catch (error) {
      console.error('扔出漂流瓶失败:', error);
      res.status(500).json({
        code: 500,
        success: false,
        message: error.message || '服务器内部错误'
      });
    }
  }
);

/**
 * 捡起漂流瓶
 * POST /drift-bottles/pick
 */
router.post('/pick', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.userId;

    // 随机捡起一个漂流瓶
    const bottle = await DriftBottle.pickRandom(userId);

    if (!bottle) {
      return res.status(404).json({
        code: 404,
        success: false,
        message: '暂时没有可捡起的漂流瓶，请稍后再试'
      });
    }

    res.json({
      code: 200,
      success: true,
      message: '成功捡起漂流瓶',
      data: {
        bottleId: bottle.id,
        content: bottle.content,
        pickCount: bottle.pickCount,
        createdAt: bottle.createdAt,
        sender: {
          userId: bottle.sender.userId,
          nickName: bottle.sender.nickName,
          avatar: bottle.sender.avatar,
          email: bottle.sender.email
        }
      }
    });
  } catch (error) {
    console.error('捡起漂流瓶失败:', error);
    res.status(500).json({
      code: 500,
      success: false,
      message: error.message || '服务器内部错误'
    });
  }
});

/**
 * 获取我发送的漂流瓶列表（可选功能）
 * GET /drift-bottles/my-sent
 */
router.get('/my-sent', 
  authenticateToken,
  [
    body('page').optional().isInt({ min: 1 }).withMessage('页码必须是正整数'),
    body('limit').optional().isInt({ min: 1, max: 50 }).withMessage('每页数量必须在1-50之间')
  ],
  async (req, res) => {
    try {
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({
          code: 400,
          success: false,
          message: '参数验证失败',
          errors: errors.array()
        });
      }

      const userId = req.user.userId;
      const page = parseInt(req.query.page) || 1;
      const limit = parseInt(req.query.limit) || 10;

      const result = await DriftBottle.getUserSentBottles(userId, page, limit);

      res.json({
        code: 200,
        success: true,
        message: '获取发送的漂流瓶列表成功',
        data: result
      });
    } catch (error) {
      console.error('获取发送的漂流瓶列表失败:', error);
      res.status(500).json({
        code: 500,
        success: false,
        message: error.message || '服务器内部错误'
      });
    }
  }
);

/**
 * 获取我捡起的漂流瓶列表（可选功能）
 * GET /drift-bottles/my-picked
 */
router.get('/my-picked', 
  authenticateToken,
  [
    body('page').optional().isInt({ min: 1 }).withMessage('页码必须是正整数'),
    body('limit').optional().isInt({ min: 1, max: 50 }).withMessage('每页数量必须在1-50之间')
  ],
  async (req, res) => {
    try {
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({
          success: false,
          message: '参数验证失败',
          errors: errors.array()
        });
      }

      const userId = req.user.userId;
      const page = parseInt(req.query.page) || 1;
      const limit = parseInt(req.query.limit) || 10;

      const result = await DriftBottle.getUserPickedBottles(userId, page, limit);

      res.json({
        code: 200,
        success: true,
        message: '获取捡起的漂流瓶列表成功',
        data: result
      });
    } catch (error) {
      console.error('获取捡起的漂流瓶列表失败:', error);
      res.status(500).json({
        success: false,
        message: error.message || '服务器内部错误'
      });
    }
  }
);

module.exports = router;